package com.jtpay.sdk.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.jtpay.sdk.holder.BaseViewHolder;

import java.util.List;


/**
 * Created by steven on 2016/2/16
 * Listview common adapter
 */
public abstract class CommonAdapter<T> extends BaseAdapter {
    private List<T> mList;
    private int mLayoutId;

    public CommonAdapter(List<T> list, int id) {
        mList = list;
        mLayoutId = id;
    }

    public CommonAdapter(List<T> list) {
        mList = list;
    }

    public void addData(T data) {
        if (null != mList) {
            mList.add(0, data);
        }
        notifyDataSetChanged();
    }

    public void setList(List<T> list) {
        mList = list;
        notifyDataSetChanged();
    }

    public List<T> getList() {
        return mList;
    }

    @Override
    public int getCount() {
        return (null == mList) ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private BaseViewHolder onCreateViewHolder(View view) {
        return new BaseViewHolder(view);
    }

    public BaseViewHolder createViewHolder(View view) {
        BaseViewHolder baseViewHolder = onCreateViewHolder(view);
        return baseViewHolder;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        BaseViewHolder baseViewHolder;
        if (convertView == null) {
            convertView = createParentView(parent, mLayoutId);
            baseViewHolder = createViewHolder(convertView);
            convertView.setTag(baseViewHolder);
        } else {
            baseViewHolder = (BaseViewHolder) convertView.getTag();
        }

        onBindViewHolder(baseViewHolder, mList.get(position), position);
        return convertView;
    }

    protected abstract void onBindViewHolder(BaseViewHolder viewHolder, T t, int position);

    protected abstract View createParentView(View view, int id);
}
